<template>
  <a-modal :width="950" ref="formRef" v-model:visible="showEditDialog" :title="currentItem.id ? '新增报价' : '编辑报价'" top="8vh" title-align="start" okText="保存" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @close="closedDialog">
    <div class="flex">
      <div class="img-w">
        <yfn-upload @success="uploadSuccess">
          <template #upload-button>
            <div class="arco-upload-list-item">
              <div class="arco-upload-list-picture custom-upload-avatar" v-if="formInfo.productImg">
                <img :src="formInfo.productImg" style="object-fit: contain" />
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
            </div>
          </template>
        </yfn-upload>
      </div>
      <a-form ref="formRef" :model="formInfo" :rules="rules">
        <a-row>
          <a-col :span="18">
            <a-form-item field="productName" label="材质名称：" label-col-flex="120px">
              <a-input v-model="formInfo.productName" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="11">
            <a-form-item field="sku" label="材质编号：" label-col-flex="120px">
              <p v-if="currentItem.id">{{ formInfo.sku }}</p>
              <a-input v-else v-model="formInfo.sku" />
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item field="unit" label="计量单位：" label-col-flex="100px">
              <p v-if="currentItem.id">{{ formInfo.unit }}</p>
              <a-input v-else v-model="formInfo.unit" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-item label="列表显示：" label-col-flex="120px">
              <a-switch v-model="formInfo.display" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="显示排序：" label-col-flex="100px">
              <a-input-number style="width: 120px" v-model="formInfo.sort" hide-button />
              <span class="tip" style="margin-left: 10px">数字越小排序越靠前</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="11">
            <a-form-item field="quotePrice" label="当前最新报价：" label-col-flex="120px">
              <a-input-number v-model="formInfo.quotePrice" hide-button />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="报价公式：" label-col-flex="120px">
              <div>
                <div class="flex-c">
                  <a-select v-model="formula.nameInfo" value-key="id" style="width: 140px">
                    <a-option v-for="(item, i) in quoteList" :key="i" :label="item.productName" :value="item" :disabled="item.id == currentItem.id" />
                  </a-select>
                  <a-select v-model="formula.formula2" style="width: 60px">
                    <a-option v-for="(val, key) in symbolMap" :key="key" :label="val" :value="key" />
                  </a-select>
                  <span>（</span>
                  <a-input-number v-model="formula.formula3" hide-button style="width: 80px" />
                  <a-select v-model="formula.formula4" style="width: 60px">
                    <a-option v-for="(val, key) in symbolMap" :key="key" :label="val" :value="key" />
                  </a-select>
                  <a-input-number v-model="formula.formula5" hide-button style="width: 80px" />
                  <span>）</span>
                  <a-select v-model="formula.formula6" style="width: 60px">
                    <a-option v-for="(val, key) in symbolMap" :key="key" :label="val" :value="key" />
                  </a-select>
                  <a-input-number v-model="formula.formula7" hide-button style="width: 80px" />
                  <a-button type="text" style="margin-left: 10px" @click="initFormula">一键清除</a-button>
                </div>
                <p class="tip" style="margin-top: 10px; width: 450px">注：报价公式是根据已有的原材质报价来计算出当前原材质报价，这样就方便操作员需设置某一个原材质的报价就能自动生成相关原材质报价；</p>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, PropType, onMounted } from 'vue'
  import { cloneDeep } from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  import { createMaterialQuote, updateMaterialQuote } from '@/api/system'

  onMounted(initDefautl)

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    quoteList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })
  const showEditDialog = ref(props.isShow)
  const symbolMap = {
    '+': '加',
    '-': '减',
    '*': '乘',
    '/': '除',
  }
  const formInfo = ref<any>({
    display: true,
  })
  const originFormula = ref<any>({
    formula2: '*',
    formula4: '*',
    formula6: '*',
  })
  const formula = ref<any>({})
  const formRef = ref()

  const submitLoading = ref(false)
  const rules = ref({
    productName: [{ required: true, message: '请输入材质名称' }],
    sku: [{ required: true, message: '请输入材质编号' }],
    unit: [{ required: true, message: '请输入计量单位' }],
    quotePrice: [{ required: true, message: '请输入当前最新报价' }],
  })

  function initDefautl() {
    let _currentVal = props.currentItem
    if (_currentVal.id) {
      formInfo.value = {
        id: _currentVal.id,
        productImg: _currentVal.productImg,
        productName: _currentVal.productName,
        sku: _currentVal.sku,
        unit: _currentVal.unit,
        display: _currentVal.display,
        sort: _currentVal.sort,
        quotePrice: _currentVal.quotePrice,
      }
      if (_currentVal.formula1) {
        formula.value = {
          nameInfo: {
            id: _currentVal.formula1,
            productName: _currentVal.formula1Name,
          },
          formula2: _currentVal.formula2 || originFormula.value.formula2,
          formula3: Number(_currentVal.formula3),
          formula4: _currentVal.formula4 || originFormula.value.formula4,
          formula5: Number(_currentVal.formula5),
          formula6: _currentVal.formula6 || originFormula.value.formula6,
          formula7: Number(_currentVal.formula7),
        }
      }
    } else {
      initFormula()
    }
  }

  function initFormula() {
    formula.value = cloneDeep(originFormula.value)
  }
  // 图片上传
  function uploadSuccess(info: any) {
    formInfo.value.productImg = info?.url
  }

  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  function getSavaData() {
    let _params: any = {
      ...formInfo.value,
    }
    let _formula = JSON.parse(JSON.stringify(formula.value))
    if (_formula?.nameInfo?.id) {
      _formula.formula1 = _formula.nameInfo.id
      _formula.formula1Name = _formula.nameInfo.productName
      delete _formula.nameInfo
      _params = {
        ..._params,
        ..._formula,
      }
    }
    return _params
  }
  // 保存
  async function submitData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let params = getSavaData()
    let res: any
    if (params.id) {
      res = await updateMaterialQuote(params)
    } else {
      res = await createMaterialQuote(params)
    }
    if (!res) return false
    Message.success('报价保存成功')
    emit('success')
    emit('closed')
    return true
  }
</script>

<style lang="less" scoped>
  :deep(.arco-form-item-label-col) {
    padding-right: 5px;
  }
  .arco-upload-list-picture {
    width: 100px;
    height: 100px;
  }
  .img-w {
    width: 120px;
    height: 120px;
    flex-shrink: 0;
  }
  .arco-upload-list-item {
    margin-top: 0;
  }
  .tip {
    color: #999;
    font-size: 12px;
  }
</style>
